<template>
    <div class="page-wrap page-wrap-ql">
        <div class="page-cont">
            <a-page-header @back="handleBack">
                <template #title> 产线汇报设置 </template>
            </a-page-header>
            <div style="padding: 16px 42px 0 42px">
                <filter-form @change="handleChange" />
            </div>
            <h-section title="报告的系统/产线设置" collapse style="padding: 0 24px">
                <template #titleExtra>
                    <flexbox justify="flex-end">
                        <a-button @click.stop="handleAdd" type="primary">添加系统</a-button>
                    </flexbox>
                </template>
                <CustomTable autoResize rowKey="id" size="small" :loading="loading" :columns="tableColumns" :data-source="list" :pagination="paginationConfig" @change="handleTableChange">
                    <template #customMonthTitle>
                        <a-checkbox v-model:checked="isMonthCheckAll" :indeterminate="isMonthIndeterminate" @change="onCheckAllChange($event, 'isMonth')">
                            <a-tooltip title="在每月的最后一日统计当月数据并发起汇报流程">
                                月汇报
                                <QuestionCircleOutlined />
                            </a-tooltip>
                        </a-checkbox>
                    </template>
                    <template #customQuarterTitle>
                        <a-checkbox v-model:checked="isQuarterCheckAll" :indeterminate="isQuarterIndeterminate" @change="onCheckAllChange($event, 'isQuarter')">
                            <a-tooltip title="在3/6/9/12月的最后一日统计前（包含当月）三月数据并发起汇报流程">
                                季度汇报
                                <QuestionCircleOutlined />
                            </a-tooltip>
                        </a-checkbox>
                    </template>
                    <template #customHalfYearTitle>
                        <a-checkbox v-model:checked="isHalfYearCheckAll" :indeterminate="isHalfYearIndeterminate" @change="onCheckAllChange($event, 'isHalfYear')">
                            <a-tooltip title="在每年6月31日统计1-6月数据并发起汇报流程">
                                半年度汇报
                                <QuestionCircleOutlined />
                            </a-tooltip>
                        </a-checkbox>
                    </template>
                    <template #customYearTitle>
                        <a-checkbox v-model:checked="isYearCheckAll" :indeterminate="isYearIndeterminate" @change="onCheckAllChange($event, 'isYear')">
                            <a-tooltip title="在每年12月31日统计当年数据并发起汇报流程">
                                年度汇报
                                <QuestionCircleOutlined />
                            </a-tooltip>
                        </a-checkbox>
                    </template>
                    <template #month="{ record }">
                        <a-checkbox v-model:checked="record.isMonth" @change="checkChange($event, 'isMonth')" />
                    </template>
                    <template #quarter="{ record }">
                        <a-checkbox v-model:checked="record.isQuarter" @change="checkChange($event, 'isQuarter')" />
                    </template>
                    <template #halfYear="{ record }">
                        <a-checkbox v-model:checked="record.isHalfYear" @change="checkChange($event, 'isHalfYear')" />
                    </template>
                    <template #year="{ record }">
                        <a-checkbox v-model:checked="record.isYear" @change="checkChange($event, 'isYear')" />
                    </template>
                    <template #isOutsideSystem="{ text }">
                        {{ text === '1' ? '外部' : '内部' }}
                    </template>
                    <template #action="{ record }">
                        <a @click="handleRemove(record)">移除</a>
                    </template>
                </CustomTable>
            </h-section>
        </div>
        <add-system-modal ref="addSystemModalRef" @success="getList" />
    </div>
</template>

<script lang="ts">
import api from '@/api';
import FilterForm from './components/FilterForm.vue';
import { CustomTable } from '@/components';
import { usePagination } from '@/components/Table/hooks';
import { deepClone } from '@/utils/util';
import { useMessage } from '@/hooks/common/useMessage';
import { message } from 'ant-design-vue/es';
import AddSystemModal from './components/AddSystemModal.vue';
import { QuestionCircleOutlined } from '@ant-design/icons-vue';
import { useRouterApi } from '@/hooks/common/useRouterApi';
import { defineComponent, ref, unref, reactive, toRefs } from 'vue';
export default defineComponent({
    components: {
        QuestionCircleOutlined,
        AddSystemModal,
        FilterForm,
        CustomTable
    },
    setup() {
        const addSystemModalRef = ref<any>();
        const { paginationConfig, setPaginationConfig } = usePagination();
        const { handleBack } = useRouterApi({
            backQuery: {
                path: '/setting'
            }
        });
        const tableColumns = [
            {
                title: '系统名称',
                dataIndex: 'systemName'
            },
            {
                title: '数据来源',
                dataIndex: 'isOutsideSystem',
                slots: { customRender: 'isOutsideSystem' }
            },
            {
                dataIndex: 'month',
                slots: { customRender: 'month', title: 'customMonthTitle' }
            },
            {
                dataIndex: 'quarter',
                slots: { customRender: 'quarter', title: 'customQuarterTitle' }
            },
            {
                dataIndex: 'halfYear',
                slots: { customRender: 'halfYear', title: 'customHalfYearTitle' }
            },
            {
                dataIndex: 'year',
                slots: { customRender: 'year', title: 'customYearTitle' }
            },
            {
                title: '操作',
                dataIndex: '',
                key: 'action',
                slots: { customRender: 'action' }
            }
        ];
        const state = reactive<any>({
            loading: false,
            list: [],
            isMonthIndeterminate: false,
            isQuarterIndeterminate: false,
            isHalfYearIndeterminate: false,
            isYearIndeterminate: false,
            isMonthCheckAll: false,
            isQuarterCheckAll: false,
            isHalfYearCheckAll: false,
            isYearCheckAll: false,
            searchQuery: {}
        });
        const checkChange = (val, type, init = false) => {
            const checkedArr = state.list.filter((item) => item[type]);
            state[`${type}Indeterminate`] = checkedArr.length ? checkedArr.length < state.list.length : false;
            state[`${type}CheckAll`] = checkedArr.length ? checkedArr.length === state.list.length : false;
            !init && handleSave();
        };
        // 批量操作
        const onCheckAllChange = (e, type) => {
            const res = e.target.checked;
            state.list.forEach((item) => (item[type] = res));
            handleSave();
        };
        const handleSave = async () => {
            let list: any = deepClone(state.list);
            list = list.map((item) => ({
                ...item,
                isMonth: item.isMonth ? '1' : '0',
                isQuarter: item.isQuarter ? '1' : '0',
                isHalfYear: item.isHalfYear ? '1' : '0',
                isYear: item.isYear ? '1' : '0'
            }));
            const { success, errorMsg } = await api.requireReportModel.saveSystemReportSetting([...list]);
            if (!success) {
                message.error(errorMsg);
            }
        };
        const handleAdd = () => {
            unref(addSystemModalRef).open();
        };
        const handleRemove = async (val) => {
            const { createConfirm } = useMessage();
            createConfirm({
                title: `确认移除${val.systemName}?`,
                iconType: 'warning',
                okText: '确认',
                keyboard: false,
                onOk: async () => {
                    const query = {
                        ...val,
                        isSettingReport: '0'
                    };
                    const { success, errorMsg } = await api.requireReportModel.saveSystemReportSetting([query]);
                    if (success) {
                        message.success('移除成功');
                        getList();
                    } else {
                        message.error(errorMsg);
                    }
                }
            });
        };
        const getList = async () => {
            state.loading = true;
            const { success, moule, totalCount } = await api.requireReportModel.findSetReportSystems(state.searchQuery);
            if (success) {
                if (moule.length) {
                    state.list = moule.map((item) => ({
                        ...item,
                        isMonth: !!+item.isMonth,
                        isQuarter: !!+item.isQuarter,
                        isHalfYear: !!+item.isHalfYear,
                        isYear: !!+item.isYear
                    }));
                    checkChange('', 'isMonth', true);
                    checkChange('', 'isQuarter', true);
                    checkChange('', 'isHalfYear', true);
                    checkChange('', 'isYear', true);
                } else {
                    state.list = [];
                }
                setPaginationConfig({
                    total: totalCount
                });
            }
            state.loading = false;
            return success;
        };
        const handleTableChange = (val) => {
            setPaginationConfig(val);
            getList();
        };
        const handleChange = (query) => {
            setPaginationConfig({
                current: 1
            });
            state.searchQuery = {
                ...query
            };
            getList();
        };
        getList();
        return {
            tableColumns,
            addSystemModalRef,
            ...toRefs(state),
            handleBack,
            checkChange,
            onCheckAllChange,
            handleAdd,
            getList,
            handleRemove,
            handleChange,

            paginationConfig,
            handleTableChange
        };
    }
});
</script>
<style scoped lang="less">
.page-wrap {
    height: 100%;
    position: relative;
    .page-cont {
        background: #fff;
        .btn-group {
            margin: 24px 0;
            button + button {
                margin-left: 8px;
            }
        }
    }
}
</style>